package com.fengxing.ams.web.facade;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.fengxing.ams.web.action.view.SysCodeQueryVO;
import com.fengxing.ams.web.facade.intf.ISysManagerFacade;
import com.fengxing.ams.web.facade.mouble.sys.ISysCodeDAO;
import com.fengxing.ams.web.facade.mouble.sys.SysCodeVO;
import com.fengxing.ams.web.facade.mouble.user.IRoleDAO;
import com.fengxing.ams.web.facade.mouble.user.IUserDAO;
import com.fengxing.ams.web.facade.mouble.user.RoleVO;
import com.fengxing.ams.web.facade.mouble.user.UserVO;

@Component
@Transactional
public class SysManagerFacade implements ISysManagerFacade {

	@Autowired
	ISysCodeDAO sysCodeDAO;
	@Autowired
	IRoleDAO roleDAO;
	@Autowired
	IUserDAO userDAO;
	
	@PersistenceContext
    protected EntityManager em;  
   
	@Transactional(readOnly = false)
    public void batchInsert(List list) {
    	
        for(int i = 0; i < list.size(); i++) {
            em.persist(list.get(i));
            if((i != 0 && i % 30== 0) || i == list.size() - 1) {
                em.flush();  
                em.clear();  
            }
        }  
    }
	
	public List<String> getChannels() {
		return this.sysCodeDAO.getChannels();
	}

	@Override
	public SysCodeVO getCodeById(String id) {
		return this.sysCodeDAO.getCodeForUpdate(id);
	}

	public void save(List<SysCodeVO> allCode) {
		this.batchInsert(allCode);
	}

	public void userActiveVip(UserVO userVO, SysCodeVO codeVO) {
		//更新激活码状态
		codeVO.setStatus(2);
		codeVO.setActiveDate(new Date());
		codeVO.setUserEmail(userVO.getEmail());
		this.sysCodeDAO.save(codeVO);
		
		//更新用户角色
		Integer roleId = codeVO.getRole();
		RoleVO role = roleDAO.findOne(roleId.longValue());
		
		
		List<RoleVO> roleList = new ArrayList<RoleVO>();
		roleList.add(role);
		userVO.setRoleList(roleList);
		
		this.userDAO.save(userVO);
		
	}

	@Override
	public List<SysCodeVO> query(SysCodeQueryVO queryVO) {
		return this.sysCodeDAO.queryCodeByQueryVO(queryVO.getQ_channel(), queryVO.getQ_role(), queryVO.getQ_status(), queryVO.getCreated_email());
	}

	@Override
	public SysCodeVO findOneCodeCanUse(String channel) {
		return this.sysCodeDAO.getOneCodeForUpdate(channel);
	}
	
}
